/*
 
 */
#include <EEPROM.h>
#include <avr/interrupt.h>
#include <avr/io.h>

#define INIT_TIMER_COUNT 6
#define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT

// One and two phases
// 60000ms / 48steps = 1250ms/step
#define TRACK  1250

int ledPin = 13;    // LED connected to digital pin 9
volatile int tmp = 0;
int input = 0;
volatile int delayvalue = 500;
bool led_state = LOW;
int int_counter = 0;

// Aruino runs at 16 Mhz, so we have 1000 Overflows per second...
// 1/ ((16000000 / 64) / 256) = 1 / 1000
ISR(TIMER2_OVF_vect) {
  RESET_TIMER2;
  int_counter++;
  if(!(int_counter%TRACK))
  {
    led_state = not led_state;
    digitalWrite(ledPin, led_state);   // set the LED on/off
  }
};


//This function will write a 2 byte integer to the eeprom at the specified address and address + 1
void EEPROMWriteInt(int p_address, int p_value)
	{
	byte lowByte = ((p_value >> 0) & 0x00FF);
	byte highByte = ((p_value >> 8) & 0x000F);

	EEPROM.write(2*p_address, lowByte);
	EEPROM.write((2*p_address) + 1, highByte);
	}

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
unsigned int EEPROMReadInt(int p_address)
	{
	byte lowByte = EEPROM.read(2*p_address);
	byte highByte = EEPROM.read((2*p_address) + 1);

  	return ((lowByte << 0) & 0x00FF) + ((highByte << 8) & 0x0F00);
	}


// The setup() method runs once, when the sketch starts

void setup()   {                
  // initialize the digital pin as an output:
  pinMode(ledPin, OUTPUT);  
  Serial.begin(9600);  

  pinMode(2, INPUT);  
  attachInterrupt(0, int_handler, RISING); // 0 -> pin2 | 1 -> pin3
  
  delayvalue = EEPROMReadInt(0 /*addr*/);

  //Timer2 Settings: Timer Prescaler /64,
  TCCR2A |= (1<<CS22);
  TCCR2A &= ~((1<<CS21) | (1<<CS20));
  // Use normal mode
  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
  // Use internal clock - external clock not used in Arduino
  ASSR |= (0<<AS2);
  //Timer2 Overflow Interrupt Enable
  TIMSK2 |= (1<<TOIE2) | (0<<OCIE2A);
  RESET_TIMER2;
  sei();
}

// the loop() method runs over and over again,
// as long as the Arduino has power

void loop()                     
{
  while (Serial.available() > 0) {
    input = Serial.read();
    switch(input){
      case '?':
      Serial.println("Differnt command options: up (u) | down (d)"); break;
      case 'u':
      Serial.println("up"); delayvalue += 250; break;
      case 'd':
      Serial.println("down"); delayvalue -= 250; break;
      case 'v':
      Serial.println(delayvalue); break;
      case 'w':
      Serial.println("writing EEPROM value"); EEPROMWriteInt(0 /*addr*/, delayvalue); break;
      case 'r':
      Serial.println("resetting EEPROM value"); EEPROMWriteInt(0 /*addr*/, 500); delayvalue = 500; break;
    }
  }
  
}

void int_handler()
{
  tmp++;
  //Serial.println("Interrupt received !!!!"); 
}










